﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Space_Conquest
{

    /// <summary>
    /// Same as client, except insures client receives server's sends in correct order
    /// </summary>
    class SequentialClient : Client
    {

        List<SequenceWrapper> receiveOrder = new List<SequenceWrapper>();
        bool hasStartedReceiving = false;
        int lastInSequence = 0;
        int firstInSequence = 0;

        public SequentialClient(string serverIPAddress) :
            base(serverIPAddress)
        {



        }

        public SequentialClient(string serverIPAddress, int portNumber) :
            base(serverIPAddress, portNumber)
        {



        }

        protected override void SendReceiveEvent(object obj)
        {

            SequenceWrapper wrapper = (SequenceWrapper)obj;

            // No guarantee that client gets first send server ever makes, so start here
            if (!hasStartedReceiving)
            {

                lastInSequence = wrapper.Sequence;
                firstInSequence = lastInSequence;
                hasStartedReceiving = true;

                base.SendReceiveEvent(wrapper.Object);

            }
            else
            {

                // Drop anything accidently picked up before first receive (probably extremely rare)
                if (wrapper.Sequence > firstInSequence)
                {

                    receiveOrder.Add(wrapper);
                    receiveOrder.Sort();

                    while (receiveOrder.Count > 0)
                    {

                        if (receiveOrder[0].Sequence == lastInSequence + 1)
                        {
                            // Got in correct order, send off
                            base.SendReceiveEvent(receiveOrder[0].Object);
                            receiveOrder.RemoveAt(0);
                            ++lastInSequence;
                        }
                        else
                        {
                            // Got in wrong order, wait for the correct one
                            break;
                        }

                    }

                }


            }


        }

    }
}
